package org.aileen.java_chatroom.api;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.aileen.java_chatroom.model.Friend;
import org.aileen.java_chatroom.model.FriendMapper;
import org.aileen.java_chatroom.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class FriendAPI {
    @Resource
    private FriendMapper friendMapper;

    @GetMapping("/friendList")
    @ResponseBody//将返回值转换为 JSON 格式
    public Object getFriendList(HttpServletRequest req){//
        //1.先从 session 中获取 userId
        HttpSession session = req.getSession(false);

        if(session == null){
            //当前用户会话不存在(未登录)
            //直接返回一个空的列表即可
            System.out.println("[getFriendList] session 不存在");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");

        if (user == null){
            //当前用户对象没有在会话中存在
            System.out.println("[getFriendList] user 不存在");
            return new ArrayList<Friend>();
        }

        //2.根据 userId 从数据库查询数据
        List<Friend> friendList = friendMapper.selectFriendList(user.getUserId());
        return friendList; //返回查询到的好友列表
    }
}
